package com.cong.lru;

import java.util.HashMap;
import java.util.Map;

public class MyLruCache2 {


    class Node<K,V>{
        K key;
        V value;
        Node<K,V> prev;
        Node<K,V> next;

        public Node() {
            this.prev =this.next=null;
     
        }


        public Node(K key, V value) {
            this.key = key;
            this.value = value;
            this.prev =this.next=null;
        }
    }
    
    class DoubleLinkedList<K,V>{
        Node<K,V> head;
        Node<K,V> tail;

        public DoubleLinkedList() {
            head =new Node<>();
            tail = new Node<>();
            head.next =tail;
            tail.prev =head;
        }
    public void  addHead(Node<K,V> node){
            node.next= head.next;
            node.prev =head;
            head.next.prev = node;
            head.next =node;
    }
        public void  removeNode(Node<K,V> node){
            node.next.prev= node.prev;
            node.prev.next =node.next;
            head.prev = null;
            head.next =null;
        }

        public Node<K,V> getLast(){
            return tail.prev;
        }

    }

    private int cacheSize;
    Map<Integer,Node<Integer,Integer>> map;
    DoubleLinkedList<Integer,Integer> doubleLinkedList;

    public MyLruCache2(int cacheSize) {
        this.cacheSize = cacheSize;
        map= new HashMap<>();
        doubleLinkedList = new DoubleLinkedList<>();
    }

    public int get(Integer key){
        if (!map.containsKey(key)){
            return -1;
        }
        Node<Integer, Integer> node = map.get(key);
        doubleLinkedList.removeNode(node);
        doubleLinkedList.addHead(node);
        return node.value;
    }

    public void put(int key,int value) {
        if (map.containsKey(key)){
            //更新数据
            Node<Integer, Integer> node = map.get(key);
            doubleLinkedList.removeNode(node);
            node.value=value;
            map.put(key,node);
            doubleLinkedList.addHead(node);

        }else if (map.size()==cacheSize){
            Node<Integer, Integer> last = doubleLinkedList.getLast();
            map.remove(last.key);
            doubleLinkedList.removeNode(last);
        }
        //新增
        Node<Integer, Integer> node = new Node<>(key, value);
        map.put(key,node);
        doubleLinkedList.addHead(node);
    }

    public static void main(String[] args) {
        MyLruCache2 lruCache = new MyLruCache2(3);
        lruCache.put(1,1);
        lruCache.put(2,2);
        lruCache.put(3,3);
        lruCache.get(1);
        System.out.println(lruCache.map.keySet());
        lruCache.put(4,4);
        System.out.println(lruCache.map.keySet());
        System.out.println(lruCache.map.keySet());
    }
}
